package com.cff.springbootwork.netty.handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.cff.springbootwork.netty.model.DefaultModel;
import com.cff.springbootwork.netty.service.BusinessSerivce;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@Component
@Sharable
public class NettyServerHandler extends SimpleChannelInboundHandler<String> {

	@Autowired
	public BusinessSerivce bussinessService;

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) {
		try {
			DefaultModel defaultMqModel = JSONObject.toJavaObject(JSONObject.parseObject(msg), DefaultModel.class);

			String retMsg = bussinessService.doBusiness(defaultMqModel);
			ctx.writeAndFlush(retMsg);
		} catch (Exception e) {
			e.printStackTrace();
			String retMsg = e.getLocalizedMessage();
			ctx.writeAndFlush(retMsg);
		}
	}
}
